package com.ccys.app.controller;

import com.ccys.common.third.mailGun.MailgunUtil;
import com.ccys.common.util.HtmlUtils;
import com.ccys.common.vo.ResponseResultApp;
import com.ccys.db.cache.UserUtil;
import com.ccys.db.dto.app.addDependantScreen.AddDependantDto;
import com.ccys.db.entity.TblMember;
import com.ccys.db.entity.TblMemberFamily;
import com.ccys.db.mapper.TblMemberFamilyMapper;
import com.ccys.db.mapper.TblMemberMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * @Author：XLY
 * @Date：2024/1/31 0031
 */
@RestController
@RequestMapping("/addDependantScreen")
@Api(tags = "Add Dependant Screen")
@Slf4j
public class AddDependantScreenController {


    @Resource
    private TblMemberMapper memberMapper;

    @Resource
    private TblMemberFamilyMapper familyMapper;


    @ApiOperation("Add Dependant Screen/1")
    @PostMapping("AddDependant")
    @Transactional
    public ResponseResultApp AddDependant(@RequestBody AddDependantDto dto) {
        //根据email找到这个人的info
        Example memberExample = new Example(TblMember.class);
        memberExample.createCriteria().andEqualTo("email", dto.getEmail());
        List<TblMember> tblMembers = memberMapper.selectByExample(memberExample);
        //查询这个人是否已经添加过了，返回错误信息
        Example familyExample = new Example(TblMemberFamily.class);
        String curLoginUserId = UserUtil.getCurLoginUserId();
        familyExample.createCriteria().andEqualTo("invitedEmail", dto.getEmail()).andEqualTo("memberIdSendInvitation", curLoginUserId);
        List<TblMemberFamily> families = familyMapper.selectByExample(familyExample);
        if (CollectionUtils.isNotEmpty(families)) {
            return ResponseResultApp.error("Your dependant has already received an invitation from you previously");
        }
        //添加
        if (CollectionUtils.isNotEmpty(tblMembers)) {
            TblMember dependant = tblMembers.get(0);
            TblMemberFamily family = new TblMemberFamily();
            family.setMemberId(curLoginUserId);
            family.setDependantId(dependant.getId());
            family.setStatus(0);
            family.setCode(dependant.getNricFin());
            family.setRelationship(dto.getRelationship());
            family.setInvitedEmail(dto.getEmail());
            family.setMemberIdSendInvitation(curLoginUserId);
            familyMapper.insert(family);

        }
        TblMember curLoginMember = UserUtil.getCurLoginMember();
        if(Objects.nonNull(curLoginMember)){
            String senderName = curLoginMember.getFirstName() + ' ' + curLoginMember.getLastName();
            Integer curLoginMemberGender = curLoginMember.getGender();
            String gender = (Objects.nonNull(curLoginMemberGender) && curLoginMemberGender == 0) ? "her" : "his";

            CompletableFuture.runAsync(() -> {
                try {
                    //发送给被邀请人
                    Map<String, Object> map = new HashMap<>();
                    map.put("senderName", senderName);
                    map.put("gender", gender);
                    String templateContent = HtmlUtils.getTemplateContent("Dependant_Been_Invitation.ftl", map);
                    MailgunUtil.sendEmail(dto.getEmail(), "You Have Been Invited!", null, templateContent);

                    //发送给邀请人
                    String invitorTemplateContent = HtmlUtils.getTemplateContent("Add_Dependant_Invitation.ftl", map);
                    MailgunUtil.sendEmail(curLoginMember.getEmail(), "Your Invitation Has Been Sent!", null, invitorTemplateContent);

                } catch (Exception e) {
                    log.error(e.getMessage());
                }
            });
        }

        return ResponseResultApp.success();
    }
}
